import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

import 'lib_apple_auth_storage_platform_interface.dart';

/// An implementation of [LibAppleAuthStoragePlatform] that uses method channels.
class MethodChannelLibAppleAuthStorage extends LibAppleAuthStoragePlatform {
  /// The method channel used to interact with the native platform.
  @visibleForTesting
  final methodChannel = const MethodChannel('lib_apple_auth_storage');

  @override
  Future<String?> getPlatformVersion() async {
    final version =
        await methodChannel.invokeMethod<String>('getPlatformVersion');
    return version;
  }

  @override
  Future<AppleLoginResult?> login() async {
    try {
      var result = await methodChannel.invokeMethod<String>('login');

      Map<String, dynamic> result_json = jsonDecode(result!);
      String code = result_json["code"];
      if (code == '0') {
        return AppleLoginResult(
            result_json['userID'], result_json['identityToken']);
      } else {
        return null;
      }
    } catch (e) {
      return null;
    }
  }

  @override
  Future<bool> storage(String fileName, String? content) async {
    Map<String, dynamic> args = {
      'fileName': fileName,
      'content': content,
    };

    var json = jsonEncode(args);

    try {
      var result = await methodChannel.invokeMethod<String>('storage', json);
      Map<String, dynamic> result_json = jsonDecode(result!);
      String code = result_json["code"];
      if (code == '0') {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      return false;
    }
  }

  @override
  Future<String?> getStorageContent(String fileName) async {
    try {
      Map<String, dynamic> args = {
        'fileName': fileName,
      };
      var json = jsonEncode(args);
      var result =
          await methodChannel.invokeMethod<String>('getStorageContent', args);
      Map<String, dynamic> result_json = jsonDecode(result!);
      String code = result_json["code"];
      if (code == '0') {
        return result_json["fileContent"];
      } else {
        return null;
      }
    } catch (e) {
      return null;
    }
  }
}
